package job.manager.security.connector;

import java.util.HashSet;
import java.util.Set;
import job.manager.client.mb.ConnectFactory;
import job.manager.db.ec.UserGroupsEB;
import job.manager.db.ec.UsersEB;
import job.manager.db.sb.UserRemote;
import job.manager.security.app.AppUser;
import job.manager.security.interfaces.AppUserInt;
import job.manager.security.interfaces.UserDataConnectorInt;

/**
 *  Collects user from database and creates a application user
 *  adding the roles to the application user
 *  (roles determine what the user are going to see in the application)
 *
 */

public class UserDataConnector implements UserDataConnectorInt {


    // finds the user from the datanase and creates a application user if it is found
    public AppUserInt findUser(String userName) {
        UserRemote userBean = this.lookupUserBean();
        UsersEB user = null;
        try {
            user = userBean.findUser(userName);
        }catch(Exception e) { //if not found return null so caller nows
            return null;
        }
        Set<String> roles = new HashSet<String>();
        if(user.getIsAdmin()) { // if admin we want full acces to all
            for( UserGroupsEB group : userBean.getUserGroups() ) {
                roles.add("ROLE_" + group.getGroupName().toUpperCase());
            }
        }else {
            roles.add("ROLE_" + user.getUsergroup().getGroupName().toUpperCase());
        }
        return new AppUser(user.getUserName(),user.getPassword(),user.getEmail(),roles);
    }

    //get the UserBean
    private UserRemote lookupUserBean() {
        return ConnectFactory.getUserBean();
    }

}
